package top.zlhy7.exception.handler;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.zlhy7.base.response.ResultVO;
import top.zlhy7.exception.ServiceException;

import java.util.stream.Collectors;

/**
 * @author renyong
 * @date 2023/7/9 18:18
 * @description 全局异常处理
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {
    /**
     * 参数校验异常
     * @param e
     * @return
     * @author renyong on 2023/7/9 18:19
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult().getAllErrors().stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ResultVO.error(errorMsg);
    }
    /**
     * 业务异常信息
     * @param e
     * @return
     * @author renyong on 2024-09-29 19:31:31
     */
    @ExceptionHandler(ServiceException.class)
    public ResultVO<String> serviceExceptionHandler(ServiceException e) {
        return ResultVO.error(e.getMessage());
    }
    /**
     * 参数校验异常
     * @param e
     * @return
     * @author renyong on 2023/7/9 18:19
     */
    @ExceptionHandler(Exception.class)
    public ResultVO<String> exceptionHandler(Exception e) {
        return ResultVO.error("服务异常");
    }
}
